import { fetchEventSource } from '@microsoft/fetch-event-source';
import { baseUrl } from '@/api/globalConfig'
class AiModel {
    static chat(question, prompt, onMessage, onEnd) {
        let ctrl = new AbortController();
        const Authorization = localStorage.getItem("me_token") || "";
        return fetchEventSource(`${baseUrl}/ai/getAiChatStream`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": Authorization
            },
            openWhenHidden: true,
            body: JSON.stringify({ question, autoSave: false, prompt }),
            signal: ctrl?.signal,
            onmessage: (event) => {
                const data = event.data || ''
                if (data === '[DONE]') {
                    onEnd();
                    ctrl.abort()
                    return;
                }

                const obj = JSON.parse(data) // 服务端每次 res.write 返回的信息
                if (obj.Done) {
                    let id = obj.id;
                    onEnd(id);
                    ctrl.abort()
                    return;
                }
                const content = obj.choices[0].delta.content
                if (content === null || content === undefined) {
                    console.log('stop...')  // 可能因为其他原因停止
                    onEnd();
                    return;
                }
                onMessage(content);
                // console.log(content)
            },
            onclose() {
                console.log('close')
            },
            onerror(err) {
                ctrl.abort()
                throw err // 直接抛出错误，避免反复调用
            }
        })
    }
}

export default AiModel;